﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Filters;
using EPiServer.Framework.Web;
using EPiServer.ServiceLocation;
using EPiServer.Web;

namespace EPiBoost.Core.Filters.PageFilters
{
    public class FilterCanRender : IPageFilter
    { 
    	private string m_Tag;

        public FilterCanRender(string tag = null)
        {
        	m_Tag = tag;
        }
		  
        public void Filter(PageDataCollection pages)
        {
			for (int i = pages.Count - 1; i >= 0; i--)
			{
				if (!CanRender(pages[i]))
				{
					pages.RemoveAt(i);
				}
			} 
        }

		private bool CanRender(PageData page)
		{
			var templateResolver = ServiceLocator.Current.GetInstance<TemplateResolver>();
			var context = new HttpContextWrapper(HttpContext.Current);
			TemplateModel templateModel = templateResolver.Resolve(context, page.GetOriginalType(), page, TemplateTypeCategories.MvcPartial, m_Tag);
			

			return  templateModel != null;
		}


        public void Filter(object sender, FilterEventArgs e)
        {
            Filter(e.Pages);
        }

        public bool ShouldFilter(PageData page)
        {
            throw new NotImplementedException();
        }
    }
}
